<?php
error_reporting(E_ALL & ~E_NOTICE);
// 定义当前模块路径
define('MODULE_PATH', APP_PATH . \think\Request::instance()->module() . '/');
/**
 * 创建数据表
 * @param  resource $db 数据库连接资源
 */
function create_tables($db, $prefix = '')
{
    $sql = file_get_contents(MODULE_PATH . 'data/install.sql');
    $sql = str_replace("\r", "\n", $sql);
    $sql = explode(";\n", $sql);
   
        //替换表前缀
    $orginal = 'fmg_'; 
    $sql = str_replace(" `{$orginal}", " `{$prefix}", $sql);
    //开始安装
    foreach ($sql as $value) 
    {
        $value = trim($value);
        if (empty($value)) 
        {
            continue;
        }
        if (substr($value, 0, 12) == 'CREATE TABLE') 
        {
            $name = preg_replace("/^CREATE TABLE `(\w+)` .*/s", "\\1", $value);
            if (false !== $db->execute($value)) 
            {
            } 
            else 
            {
            }
        } else {
            $db->execute($value);
        }                
    }        
}
/**
 * 用户帐号注册
 * @param  array $config 用户帐号注册
 */
function register_admin($db, $prefix, $admin)
{
    
    $sql = "INSERT INTO `[PREFIX]user` VALUES " .
    "('null', '[username]', '[password]', '[mail]','[create_time]')";
   $password = md5($admin['password']);
    $sql      = str_replace(
        array('[PREFIX]','[username]', '[password]', '[mail]', '[create_time]'),
        array($prefix,$admin['username'], $password, $admin['email'], time()),
        $sql);
    //执行sql
    $db->execute($sql);
    #return $sql;
    return '用户新增成功';
}



/**
 * 写入配置文件
 * @param  array $config 配置信息
 */
function write_config($config)
{
    if (is_array($config))
    {
        //读取配置内容
        $database = file_get_contents(MODULE_PATH . 'data/database.tpl');
        //替换配置项
        foreach ($config as $name => $value)
        {
            $database = str_replace("[{$name}]", $value, $database);
        } 
        //写入应用配置文件

            if (file_put_contents(APP_PATH . 'database.php', $database))
            {
                return '写入配置文件成功';
            }
            else
            {
                return '写入配置文件失败';
            }

    }


    
}